// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const userCollection = db.collection('user')
const cmtCollection = db.collection('comment')
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let commentList = []
  let replyList = []
  await cmtCollection.where({
    authorId: wxContext.OPENID,
    commentatorId: _.neq(wxContext.OPENID),
    commentDate: _.gte(new Date().getTime() - 30 * 24 * 3600 * 1000)
  }).orderBy('commentDate', 'desc').get().then(res => {
    commentList = res.data
  })

  await cmtCollection.where({
    commentatorId: wxContext.OPENID,
    authorId: _.neq(wxContext.OPENID),
    reply: _.neq(''),
    replyDate: _.gte(new Date().getTime() - 30 * 24 * 3600 * 1000)
  }).orderBy('replyDate', 'desc').get().then(res => {
    replyList = res.data
  })

  for (let item of commentList) {
    await userCollection.where({
      _openid: item.commentatorId
    }).get().then(res => {
      item.commentatorInfo = res.data[0]
    })
  }

  for (let item of replyList) {
    await userCollection.where({
      _openid: item.authorId
    }).get().then(res => {
      item.authorInfo = res.data[0]
    })
  }

  return {
    commentList,
    replyList
  }
}